package com.lxy.service.impl;

import com.lxy.dao.SecKillDao;
import com.lxy.dao.SuccessKilledDao;
import com.lxy.dao.redis.RedisDao;
import com.lxy.dto.Exposer;
import com.lxy.dto.SecKillExecution;
import com.lxy.enums.SecKillStateEnum;
import com.lxy.exception.RepeatException;
import com.lxy.exception.SecKillCloseException;
import com.lxy.exception.SecKillException;
import com.lxy.pojo.SecKill;
import com.lxy.pojo.SuccessKilled;
import com.lxy.service.SecKillService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SecKillService接口实现类
 *
 * @author Manaka
 * @date 2020-03-04 11:49
 */
@Service
public class SecKillServiceImpl implements SecKillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SecKillDao secKillDao;

    @Autowired
    private SuccessKilledDao successKilledDao;

    @Autowired
    private RedisDao redisDao;

    /**
     * md5盐值字符串
     */
    private final String salt = "safgfethngfhr324gfd$%^&*()dfvc54";


    /**
     * 获取所有秒杀
     *
     * @return 所有秒杀
     */
    @Override
    public List<SecKill> getSecKillList() {
        return secKillDao.queryAll(0, 4);
    }

    /**
     * 根据秒杀ID获取秒杀
     *
     * @param secKillId 秒杀ID
     * @return 秒杀
     */
    @Override
    public SecKill getById(long secKillId) {
        return secKillDao.queryById(secKillId);
    }

    /**
     * 暴露秒杀url
     *
     * @param secKillId 秒杀ID
     * @return 执行正确返回秒杀Url，否则返回当前系统时间
     */
    @Override
    public Exposer exportSecKillUrl(long secKillId) {
        /**
         * 优化点：缓存优化
         * 1、访问redis
         * 2、redis中不存在该对象 访问数据库 将结果放入redis
         */
        SecKill secKill = redisDao.getSecKill(secKillId);
        if (secKill == null) {
            secKill = secKillDao.queryById(secKillId);
            if (secKill == null) {
                return new Exposer(false, secKillId);
            } else {
                redisDao.putSecKill(secKill);
            }
        }
        Date startTime = secKill.getStartTime();
        Date endTime = secKill.getEndTime();
        //系统当前时间
        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime()
                || nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, secKillId, nowTime.getTime(), startTime.getTime(), endTime.getTime());
        }
        String md5 = getMD5(secKillId);
        return new Exposer(true, md5, secKillId);
    }

    /**
     * 根据盐值生成MD5字符串
     *
     * @param secKillId
     * @return
     */
    private String getMD5(long secKillId) {
        String base = secKillId + "/" + salt;
        //使用Spring工具类进行md5加密
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
        return md5;
    }

    /**
     * 执行秒杀逻辑
     *
     * @param secKillId 秒杀ID
     * @param userPhone 用户手机
     * @param md5       秒杀验证，不一致则秒杀失败
     * @return 秒杀处理结果
     * @throws SecKillException
     * @throws RepeatException
     * @throws SecKillCloseException
     */
    /**
     * 使用注解控制事务方法的优点：
     * 1、开发团队达成一致，明确标注事务方法的编程风格
     * 2、保证事务方法的执行时间尽可能短，不要穿插其他的网络操作RPC/HTTP请求或者剥离到事务方法外部
     * 3、不是所有的方法都需要事务，如只有一条修改操作，只读操作不需要事务控制
     */
    @Override
    @Transactional
    public SecKillExecution executeSecKill(long secKillId, long userPhone, String md5) throws SecKillException, RepeatException, SecKillCloseException {
        if (md5 == null || !getMD5(secKillId).equals(md5)) {
            throw new SecKillException("secKill data rewrite");
        }
        /**
         * 执行秒杀逻辑：减库存 + 记录购买行为
         */
        try {
            //记录购买行为
            int insertCount = successKilledDao.insertSuccessKilled(secKillId, userPhone);
            if (insertCount <= 0) {
                //重复秒杀
                throw new RepeatException("secKill repeated");
            } else {
                //减库存，热点商品竞争
                int updateCount = secKillDao.reduceNumber(secKillId, new Date());
                if (updateCount <= 0) {
                    //没有更新到记录，抛出异常
                    throw new SecKillCloseException("secKill is closed");
                } else {
                    //秒杀成功
                    SuccessKilled successKilled = successKilledDao.queryByIdWithSecKill(secKillId, userPhone);
                    return new SecKillExecution(secKillId, SecKillStateEnum.SUCCESS, successKilled);
                }
            }
        } catch (SecKillCloseException e) {
            throw e;
        } catch (RepeatException e) {
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new SecKillException("secKill inner error" + e.getMessage());
        }
    }

    @Override
    public SecKillExecution executeSecKillProducer(long secKillId, long userPhone, String md5) {
        if (md5 == null && !md5.equals(getMD5(secKillId))) {
            return new SecKillExecution(secKillId, SecKillStateEnum.DATE_REWRITE);
        }
        Date killTime = new Date();
        Map<String, Object> map = new HashMap<>();
        map.put("seckillId", secKillId);
        map.put("phone", userPhone);
        map.put("killTime", killTime);
        map.put("result", null);
        //执行完成后，result被赋值
        try {
            secKillDao.killByProcedure(map);
            //获取result的值
            Integer result = MapUtils.getInteger(map, "result", -2);
            if (result == 1) {
                SuccessKilled sk = successKilledDao.queryByIdWithSecKill(secKillId, userPhone);
                return new SecKillExecution(secKillId, SecKillStateEnum.SUCCESS, sk);
            } else {
                return new SecKillExecution(secKillId, SecKillStateEnum.stateOf(result));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new SecKillExecution(secKillId, SecKillStateEnum.INNER_ERROR);
        }
    }
}
